package com.boot.controller;

import com.boot.result.Result;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.UUID;

@RestController
@RequestMapping("/file")
@Api(description = "文件系统")
public class FileController {

    @ApiOperation("上传文件")
    @PostMapping(value = "/uploadFile", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public Result<Object> uploadFiles(HttpServletRequest req) throws ServletException, IOException {
        //       --- 接收 ---
        Part part = req.getPart("file");
        String disposition = part.getHeader("Content-Disposition");
        String suffix = disposition.substring(disposition.lastIndexOf("."), disposition.length() - 1);
        //        --- 处理 ---
        String filename = UUID.randomUUID() + suffix;
        InputStream is = part.getInputStream();
        String serverpath = req.getServletContext().getRealPath("/");
        String filePath = serverpath.substring(0, serverpath.indexOf("boot")) + "file/";
        //        --- 判断目录是否存在 ---
        File checkFile = new File(filePath);
        if (!checkFile.exists()) {
            checkFile.mkdir();
        }
        //        --- 写入文件 ---
        FileOutputStream fos = new FileOutputStream(filePath + "/" + filename);
        byte[] bty = new byte[1024];
        int length = 0;
        while ((length = is.read(bty)) != -1) {
            fos.write(bty, 0, length);
        }
        fos.close();
        is.close();
        //        --- 返回 ---
        HashMap<String, Object> info = new HashMap<>();
        info.put("url", "/file/" + filename);
        Result<Object> result = new Result<>();
        result.setCode(1);
        result.setData(info);
        result.setMessage("success");
        return result;
    }
}
